package com.samp.util;

import com.samp.base.nio.NioDemo;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

/**
 * 从指定文件中读取多少行数据，方便检查大文件。
 */
public class FileReadUtils {
    public static List<String> read(String rawPath, Integer size) throws IOException {
        Path filePath = Paths.get(rawPath);
        BufferedReader bufferReader = Files.newBufferedReader(filePath, StandardCharsets.UTF_8);
        String line;
        List<String> resultList = new ArrayList<>();
        try {
            while( (line = bufferReader.readLine()) != null ){
                if( StringUtils.isNotBlank(line) ){
                    resultList.add(line.trim());
                }
                if( resultList.size() >= size){
                    break;
                }
            }
        }finally{
            bufferReader.close();
        }
        return resultList;
    }

    /**
     * 列出目录下所有含有文件的子目录信息，包括所有下级子目录。
     * @param baseDir
     */
    public static void listSubDirs(String baseDir) throws Exception {
        Path dir = Paths.get(baseDir);
        List<String> result = new ArrayList<String>();
        Files.walkFileTree(dir, new FileReadUtils.FindJavaVisitor(result));
        System.out.println("result.size()=" + result.size());
        for(String s:result){
            System.out.println(s);
        }
    }

    private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
        private List<String> result;
        public FindJavaVisitor(List<String> result){
            this.result = result;
        }
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if( Files.isDirectory(file) ){
                //此处永远不会运行到，因为碰到文件夹会进入直接找文件
                System.out.println(file.getFileName()+"是一个文件夹."+file.toString());
            }else{
//                System.out.println(file.getFileName()+"是一个文件."+file.toString());
                String parentDir = file.getParent().toString();
//                System.out.println(file.getParent().toString());
                if( !result.contains(parentDir) ){
                    result.add(parentDir);
                }
            }
            return super.visitFile(file, attrs);
        }

    }

    public static void main(String[] args) {
        String file = "D:\\gcc-omcp\\trainning\\95511_training_06.txt";
        Integer size = 1000;
        try {
//            List<String> list = read(file, size);
//            for( String s: list ){
//                System.out.println(s);
//            }
            String basePath = "D:\\video_clean\\C\\";
            listSubDirs(basePath);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
